package com.supermarket.controller;

import com.supermarket.common.ResponseResult;
import com.supermarket.entity.DTO.OrderDTO;
import com.supermarket.entity.DTO.OrderDeliveryDTO;
import com.supermarket.entity.OrderDelivery;
import com.supermarket.entity.Rider;
import com.supermarket.service.OrderDeliveryService;
import com.supermarket.service.OrderService;
import com.supermarket.service.RiderService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 骑手控制器
 */
@RestController
@RequestMapping("/rider")
public class RiderController {

    @Resource
    private RiderService riderService;

    @Resource
    private OrderDeliveryService orderDeliveryService;
    
    @Resource
    private OrderService orderService;

    /**
     * 获取骑手信息
     *
     * @param id 骑手ID
     * @return 骑手信息
     */
    @GetMapping("/{id}")
    public ResponseResult<Rider> getRiderById(@PathVariable Integer id) {
        try {
            Rider rider = riderService.getRiderById(id);
            if (rider == null) {
                return ResponseResult.error(404, "骑手不存在");
            }
            return ResponseResult.success(rider);
        } catch (Exception e) {
            return ResponseResult.error(500, "获取骑手信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据用户ID获取骑手信息
     *
     * @param userId 用户ID
     * @return 骑手信息
     */
    @GetMapping("/user/{userId}")
    public ResponseResult<Rider> getRiderByUserId(@PathVariable Integer userId) {
        try {
            Rider rider = riderService.getRiderByUserId(userId);
            if (rider == null) {
                return ResponseResult.error(404, "该用户不是骑手");
            }
            return ResponseResult.success(rider);
        } catch (Exception e) {
            return ResponseResult.error(500, "获取骑手信息失败: " + e.getMessage());
        }
    }

    /**
     * 更新骑手状态
     *
     * @param id 骑手ID
     * @param statusMap 状态信息
     * @return 操作结果
     */
    @PutMapping("/{id}/status")
    public ResponseResult<String> updateRiderStatus(@PathVariable Integer id, @RequestBody Map<String, Object> statusMap, HttpSession session) {
        try {
            // 验证用户是否登录
            if (session.getAttribute("currentUser") == null) {
                return ResponseResult.error(401, "请先登录");
            }
            
            // 验证ID是否有效
            if (id == null) {
                return ResponseResult.error(400, "骑手ID不能为空");
            }
            
            String status = (String) statusMap.get("status");
            if (status == null || status.isEmpty()) {
                return ResponseResult.error(400, "状态参数不能为空");
            }
            
            // 验证状态值是否有效
            if (!status.equals("AVAILABLE") && !status.equals("BUSY") && !status.equals("OFFLINE")) {
                return ResponseResult.error(400, "无效的状态值");
            }
            
            boolean result = riderService.updateRiderStatus(id, status);
            if (result) {
                return ResponseResult.success("骑手状态更新成功");
            } else {
                return ResponseResult.error(400, "骑手状态更新失败");
            }
        } catch (Exception e) {
            return ResponseResult.error(500, "更新骑手状态失败: " + e.getMessage());
        }
    }

    /**
     * 获取骑手配送记录
     *
     * @param riderId 骑手ID
     * @return 包含订单详情的配送记录列表
     */
    @GetMapping("/deliveries")
    public ResponseResult<List<OrderDeliveryDTO>> getRiderDeliveries(@RequestParam Integer riderId) {
        try {
            List<OrderDelivery> deliveries = orderDeliveryService.getOrderDeliveriesByRiderId(riderId);
            List<OrderDeliveryDTO> deliveryDTOs = convertToDeliveryDTOs(deliveries);
            return ResponseResult.success(deliveryDTOs);
        } catch (Exception e) {
            return ResponseResult.error(500, "获取骑手配送记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取骑手特定状态的配送记录
     *
     * @param riderId 骑手ID（可选）
     * @param status 配送状态
     * @return 配送记录列表
     */
    @GetMapping("/deliveries/status")
    public ResponseResult<List<OrderDeliveryDTO>> getRiderDeliveriesByStatus(
            @RequestParam(required = false) Integer riderId, 
            @RequestParam String status) {
        try {
            List<OrderDelivery> deliveries;
            if (riderId != null) {
                // 获取特定骑手的特定状态订单
                deliveries = orderDeliveryService.getOrderDeliveriesByRiderIdAndStatus(riderId, status);
            } else {
                // 获取所有特定状态订单
                deliveries = orderDeliveryService.getOrderDeliveriesByStatus(status);
            }
            List<OrderDeliveryDTO> deliveryDTOs = convertToDeliveryDTOs(deliveries);
            return ResponseResult.success(deliveryDTOs);
        } catch (Exception e) {
            return ResponseResult.error(500, "获取骑手配送记录失败: " + e.getMessage());
        }
    }

    /**
     * 将配送记录转换为带有订单详情的DTO
     *
     * @param deliveries 配送记录列表
     * @return 包含订单详情的配送记录DTO列表
     */
    private List<OrderDeliveryDTO> convertToDeliveryDTOs(List<OrderDelivery> deliveries) {
        if (deliveries == null || deliveries.isEmpty()) {
            return new ArrayList<>();
        }
        
        return deliveries.stream().map(delivery -> {
            OrderDTO orderDTO = null;
            if (delivery.getOrderId() != null) {
                orderDTO = orderService.getOrderDTOById(delivery.getOrderId());
                // 确保获取地址信息
                if (orderDTO != null && orderDTO.getAddressId() != null) {
                    // 如果OrderDTO已经有地址信息，确保它能被正确使用
                    if (orderDTO.getAddressInfo() == null) {
                        // 可能需要在这里补充地址信息获取逻辑
                        System.out.println("警告：订单 " + orderDTO.getId() + " 缺少地址信息");
                    }
                }
            }
            OrderDeliveryDTO dto = OrderDeliveryDTO.fromEntities(delivery, orderDTO);
            
            // 确保一定有送达地址和联系方式
            if (dto.getDeliveryAddress() == null && orderDTO != null && orderDTO.getAddressInfo() != null) {
                dto.setDeliveryAddress(orderDTO.getAddressInfo().getDetailedAddress());
            }
            
            if (dto.getPhone() == null && orderDTO != null && orderDTO.getAddressInfo() != null) {
                dto.setPhone(orderDTO.getAddressInfo().getReceiverPhone());
            }
            
            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 获取可接单骑手列表
     *
     * @return 可接单骑手列表
     */
    @GetMapping("/available")
    public ResponseResult<List<Rider>> getAvailableRiders() {
        try {
            List<Rider> riders = riderService.getRidersByStatus("AVAILABLE");
            return ResponseResult.success(riders);
        } catch (Exception e) {
            return ResponseResult.error(500, "获取可接单骑手列表失败: " + e.getMessage());
        }
    }

    /**
     * 骑手取件
     *
     * @param deliveryMap 配送信息
     * @return 操作结果
     */
    @PutMapping("/pickup")
    public ResponseResult<String> pickupOrder(@RequestBody Map<String, Object> deliveryMap) {
        try {
            Integer deliveryId = (Integer) deliveryMap.get("deliveryId");
            
            boolean result = orderDeliveryService.updateToPickedStatus(deliveryId);
            if (result) {
                return ResponseResult.success("取件成功");
            } else {
                return ResponseResult.error(400, "取件失败，订单可能未分配给骑手");
            }
        } catch (Exception e) {
            return ResponseResult.error(500, "取件操作失败: " + e.getMessage());
        }
    }

    /**
     * 骑手送达
     *
     * @param deliveryMap 配送信息
     * @return 操作结果
     */
    @PutMapping("/deliver")
    public ResponseResult<String> deliverOrder(@RequestBody Map<String, Object> deliveryMap) {
        try {
            Integer deliveryId = (Integer) deliveryMap.get("deliveryId");
            
            boolean result = orderDeliveryService.updateToDeliveredStatus(deliveryId);
            if (result) {
                return ResponseResult.success("送达成功");
            } else {
                return ResponseResult.error(400, "送达失败，订单可能未处于取件状态");
            }
        } catch (Exception e) {
            return ResponseResult.error(500, "送达操作失败: " + e.getMessage());
        }
    }

    /**
     * 获取骑手统计信息
     *
     * @param riderId 骑手ID
     * @return 统计信息
     */
    @GetMapping("/stats")
    public ResponseResult<Map<String, Object>> getRiderStats(@RequestParam Integer riderId) {
        try {
            Rider rider = riderService.getRiderById(riderId);
            if (rider == null) {
                return ResponseResult.error(404, "骑手不存在");
            }
            
            // 获取各状态的配送单数
            List<OrderDelivery> pendingDeliveries = orderDeliveryService.getOrderDeliveriesByRiderIdAndStatus(riderId, "PENDING");
            List<OrderDelivery> assignedDeliveries = orderDeliveryService.getOrderDeliveriesByRiderIdAndStatus(riderId, "ASSIGNED");
            List<OrderDelivery> pickedDeliveries = orderDeliveryService.getOrderDeliveriesByRiderIdAndStatus(riderId, "PICKED");
            List<OrderDelivery> deliveredDeliveries = orderDeliveryService.getOrderDeliveriesByRiderIdAndStatus(riderId, "DELIVERED");
            
            // 组装统计数据
            Map<String, Object> stats = new HashMap<>();
            stats.put("riderId", rider.getId());
            stats.put("totalDeliveries", rider.getDeliveryCount());
            stats.put("rating", rider.getRating());
            stats.put("status", rider.getStatus());
            stats.put("pendingCount", pendingDeliveries.size());
            stats.put("assignedCount", assignedDeliveries.size());
            stats.put("pickedCount", pickedDeliveries.size());
            stats.put("deliveredCount", deliveredDeliveries.size());
            
            return ResponseResult.success(stats);
        } catch (Exception e) {
            return ResponseResult.error(500, "获取骑手统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 骑手领取订单
     *
     * @param claimMap 领取信息（包含deliveryId和riderId）
     * @return 操作结果
     */
    @PutMapping("/claim")
    public ResponseResult<String> claimOrder(@RequestBody Map<String, Object> claimMap) {
        try {
            Integer deliveryId = (Integer) claimMap.get("deliveryId");
            Integer riderId = (Integer) claimMap.get("riderId");
            
            if (deliveryId == null || riderId == null) {
                return ResponseResult.error(400, "配送ID和骑手ID不能为空");
            }
            
            // 获取骑手信息，验证状态
            Rider rider = riderService.getRiderById(riderId);
            if (rider == null) {
                return ResponseResult.error(404, "骑手不存在");
            }
            
            // 只有在线状态的骑手可以领取订单
            if (!"AVAILABLE".equals(rider.getStatus())) {
                return ResponseResult.error(400, "只有在线状态的骑手可以领取订单");
            }
            
            boolean result = orderDeliveryService.assignDeliveryToRider(deliveryId, riderId);
            if (result) {
                return ResponseResult.success("订单领取成功");
            } else {
                return ResponseResult.error(400, "订单领取失败，可能已被其他骑手领取");
            }
        } catch (Exception e) {
            return ResponseResult.error(500, "订单领取失败: " + e.getMessage());
        }
    }
} 